const { mysql } = require('../qcloud')

module.exports = async (ctx) => {
    const {openid, add} = ctx.request.body
    // console.log('后端接收到的数据add', add)
    // console.log('后端接收到的数据openid', openid)
    // 然后查找数据库，该用户的最新的分数是多少
    try {
        const res = await mysql('records').where('openid', openid)
                                            .select('mark')
                                            .orderBy('id', 'desc')
                                            .first()
        let mark
        if (res) {
            mark = res.mark
        } else {
            mark = 0
        }
        mark = mark + add
        console.log('处理后该用户的分数为：', mark)
        // 处理完分数了，添加到数据库中去
        await mysql('records').insert({
            openid, add, mark
        })
        ctx.state.data = {
            code: 0,
            msg: 'success',
            mark: mark
        }
        console.log('执行成功')
    } catch (error) {
        ctx.state = {
            code: -1,
            data: {
                msg: '添加失败' + error.sqlMessage
            }
        }
        console.log('执行错误')
    }
}
